﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VntNet.PowerSchemeSwitcher.Properties;
using System.Threading;
using System.Windows.Forms;

namespace VntNet.PowerSchemeSwitcher
{
    class AutoUpdateScheme
    {
        private const int CHECKTIMEOUT = 30000;
        private Dictionary<Guid, PowerPlanInfo> _planList;
        ManualResetEvent _settingUpdatedEvent;
        int _exit;

        internal event Action<bool> SettingValidated;

        public AutoUpdateScheme()
        {
            _exit = 0;
            _settingUpdatedEvent = new ManualResetEvent(false);
            ThreadPool.QueueUserWorkItem(delegate { MonitorPowerStatusThreadFn(); });
            Application.ApplicationExit += new EventHandler(Application_ApplicationExit);
        }

        void Application_ApplicationExit(object sender, EventArgs e)
        {
            Interlocked.Increment(ref _exit);
            Update();
        }
    
        internal void Update()
        {
            _settingUpdatedEvent.Set();
        }

        bool IsValidSchema(Guid schemeGuid)
        {
            return _planList.ContainsKey(schemeGuid);
        }

        void OnSettingValidated(bool result)
        {
            if (SettingValidated != null)
                SettingValidated(result);
        }

        void MonitorPowerStatusThreadFn()
        {
            while (_exit == 0)
            {
                _settingUpdatedEvent.WaitOne();
                _settingUpdatedEvent.Reset();
                if (_exit > 0)
                    break;
                _planList = PowerSchemeHelper.GetAllPowerSchemas();
                //validate settings;
                bool ValidSettings = CheckSettings();
                OnSettingValidated(ValidSettings);
                if (!ValidSettings)
                    break;
                if (Settings.Default.EnableAutoSwitching)
                {
                    //get the current line status and applay the configured sheme
                    var CurrentLineStatus=PowerLineHelper.GetCurrentSystemPowerStatus();
                    switch (CurrentLineStatus)
                    {
                        case PowerLineHelper.PowerLineStatus.Battery:
                            PowerSchemeHelper.SetPowerScheme(_planList[Settings.Default.OnFullBatteryScheme].SchemeGuid);
                            break;
                        case PowerLineHelper.PowerLineStatus.AC:
                            PowerSchemeHelper.SetPowerScheme(_planList[Settings.Default.OnAcScheme].SchemeGuid);
                            break;
                    }
                    //TODO: monitor battery % and applay low plan
                }
            }
        }

        bool CheckSettings()
        {
            int PercLow = 0;
            //TODO: reernable check when the percentage will be used
            /*
            if (!Int32.TryParse(Settings.Default.LowBatteryPercentage, out PercLow))
                return false;
            */

            if (!IsValidSchema(Settings.Default.OnAcScheme) ||
                !IsValidSchema(Settings.Default.OnFullBatteryScheme) 
                //TODO: reernable check when the percentage will be used
                /*||
                !IsValidSchema(Settings.Default.OnLowBatteryScheme)*/)
                return false;
            return true;
        }


    }
}
